<template>
  <div class="selectArea">
    <el-radio-group v-model="selectLabel" @change="changeSelect">
      <el-radio-button label="sale_">销量</el-radio-button>
      <el-radio-button label="_money">销售额</el-radio-button>
    </el-radio-group>
    <el-select v-model="selectDay" class="m-2" @change="changeSelect">
      <el-option
        v-for="item in options"
        :key="item.value"
        :label="item.name"
        :value="item.value"
      />
    </el-select>
  </div>
  <div id="pie" style="width: 100%; height: 350px"></div>
</template>

<script lang="ts" setup>
import {
  reactive,
  toRefs,
  ref,
  onMounted,
  watch,
  getCurrentInstance,
} from "vue";
import * as echarts from "echarts";
// 定义响应式数据
const state = reactive({
  selectLabel: "sale_",
  selectDay: "yesterday",
});
let { selectLabel, selectDay } = toRefs(state); // 解构数据

const options = [
  {
    name: "昨天",
    value: "yesterday",
  },
  {
    name: "今天",
    value: "today",
  },
  {
    name: "前3天",
    value: "three_days",
  },
  {
    name: "前7天",
    value: "seven_days",
  },
  {
    name: "前14天",
    value: "fourteen_days",
  },
];

let myChart: echarts.ECharts;
// 父传子数据
const props = defineProps<{
  data: { today_money: string; name: string }[];
}>();

/*
 * 方法
 */
// 修改选项
const changeSelect = () => {
  initEcharts();
};

const initEcharts = () => {
  let key = "";
  if (selectLabel.value === "_money") {
    key = selectDay.value + selectLabel.value;
  } else {
    key = selectLabel.value + selectDay.value;
  }
  console.log(key);

  const arr = props.data.map((item: { [key: string]: string }) => ({
    value: item[key],
    name: item.name,
  }));

  if (!myChart) {
    // eacharts挂载到页面
    myChart = echarts.init(document.getElementById("pie") as HTMLElement);
  }

  const option = {
    tooltip: {
      trigger: "item",
      formatter: "{b} : {c} ({d}%)",
    },
    legend: {
      type: "plain",
      height: "100px",
      top: "5%",
      left: "70%",
      orient: "vertical",
    },
    series: [
      {
        name: "Access From",
        type: "pie",
        // right: "45%",
        radius: ["40%", "70%"],
        center: ["25%", "50%"],
        data: arr,
      },
    ],
  };

  // 使用刚指定的配置项和数据显示图表。
  myChart.setOption(option);
};
watch(
  () => props.data,
  () => {
    initEcharts();
  }
);
</script>
<style lang="less" scoped>
.selectArea {
  display: flex;
  justify-content: space-between;
}
</style>
